package dyyx.cli;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import dyyx.util.CommUtil;

public class CodeLineCountMain {
	
	
	// dir  filetypes 
	
	private static String dir = null;
	private static final Set<String> fileTypes = new HashSet<String>();
	private static long count = 0;
	private static long fileCount = 0;
	private static final Set<String> files = new TreeSet<String>();


	public static void main(final String[] args) throws Exception{
		String dir = "/Users/dugang/work/gszb/salaxy-react/";
		//dir = "/Users/dugang/tmp/x/";
		fileTypes.add(".js");
		
		//dir = "/Users/dugang/tmp/s/";
		//fileTypes.add(".java");
		
		build(new File(dir));
		
		System.out.println(count);
		
		// /Users/dugang/work/gszb/salaxy-react/node_modules/@babel/polyfill
		
		
	}
	
	private static int getLines(File file) throws Exception {
		BufferedReader br = null;

		try {
			br = CommUtil.createBufferedReader(file, null);
			String line;
			int count = 0;
			while ((line = br.readLine()) != null) {
				count++;
			}

			return count;
		} finally {
			CommUtil.close(br);
		}
	}
	
	
	private static void build(File file)throws Exception {
		if(file==null){
			return;
		}
		// System.out.println(file);
		if(isSymlink(file)){
			return;
		}
		
		if(file.isDirectory()){
			String fileName = file.getName();
			if(fileName.startsWith(".") || fileName.equals("node_modules")){
				return;
			}

			File[] files = file.listFiles();
			for(File item:files){
				build(item);	   
			}
			return;
		}
		
		String fileName = file.getName();
		
		if(!fileTypeMatch(fileName)){
			return;
		}
		
		int counttmp = getLines(file);
		count = count + counttmp;
		
		
	}
	
	
	private static boolean fileTypeMatch(String fileName){
		for(String item:fileTypes){
			if(fileName.endsWith(item)){
				return true;
			}
		}
		
		return false;
	}
	
	
	public static boolean isSymlink(File file) throws IOException {
		if (file == null){
			return false;
		}
		File canon;
		if (file.getParent() == null) {
			canon = file;
		} else {
			File canonDir = file.getParentFile().getCanonicalFile();
			canon = new File(canonDir, file.getName());
		}
		return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
	}
	
	

}